package com.tfswx.jcyw.print.bean;

import javafx.beans.property.*;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import oshi.util.FormatUtil;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author 张述江
 * @date 2023/12/19
 */
@Slf4j
@Getter
public class DownloadObj {
    private final BooleanProperty visibleProperty = new SimpleBooleanProperty(false);
    private final LongProperty totalProperty = new SimpleLongProperty(0);
    private final LongProperty loadedProperty = new SimpleLongProperty(0);
    private final DoubleProperty processProperty = new SimpleDoubleProperty(0);
    private final StringProperty percentProcessProperty = new SimpleStringProperty("0%");
    private final StringProperty doanloadMxProperty = new SimpleStringProperty("第0/0页");

    private final AtomicBoolean stop = new AtomicBoolean(false);


    public DownloadObj() {
        loadedProperty.addListener((observable, oldValue, newValue) -> updateZt());
    }

    private void updateZt() {
        double process = loadedProperty.doubleValue() / totalProperty.doubleValue();
        processProperty.set(process);
        percentProcessProperty.set(((int) (process * 10000)) / 100 + "%");
        doanloadMxProperty.set(FormatUtil.formatBytes(loadedProperty.get()) + "/" + FormatUtil.formatBytes(totalProperty.get()));
        if (process == 100) {
            totalProperty.setValue(0);
            loadedProperty.setValue(0);
        }
    }

    public void updateProgress(long loaded, long total) {
        totalProperty.set(total);
        loadedProperty.set(loaded);
    }

    public void startDownload() {
        processProperty.set(0);
        percentProcessProperty.set("0%");
        doanloadMxProperty.set("0/0");
        updateZt();
        visibleProperty.set(true);
        stop.set(false);
    }

    public void completeDownload() {
        visibleProperty.set(false);
        stop.set(true);
    }

    public void cancelDownload() {
        visibleProperty.set(false);
        stop.set(true);
    }

}
